Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(low-code cdk): add flatten fields #181

Merged
merged 2 commits into from
Dec 18, 2024
Merged

Conversation

lazebnyi
Copy link
Contributor

@lazebnyi lazebnyi commented Dec 18, 2024

What

Some sources on the road to manifest only require the transformation of their records.

How

Added a FlattenFields transformation to update records to a single-level format.

Example:

  • {"FirstName": "John", "LastName": "Doe"} -> {"FirstName": "John", "LastName": "Doe"}
  • {"123Number": 123, "456Another123": 456} -> {"123Number": 123, "456Another123": 456}
  • {"NestedRecord": {"FirstName": "John", "LastName": "Doe"}, "456Another123": 456} -> {"FirstName": "John", "LastName": "Doe", "456Another123": 456}
  • {"ListExample": [{"A": "a"}, {"A": "b"}]} -> {"ListExample.0.A": "a", "ListExample.1.A": "b"}
  • {"MixedCase123": {"Nested": [{"Key": {"Value": "test1"}}, {"Key": {"Value": "test2"}}]}, "SimpleKey": "SimpleValue"} -> {"Nested.0.Key.Value": "test1", "Nested.1.Key.Value": "test2", "SimpleKey": "SimpleValue"}
  • {"List": ["Item1", "Item2", "Item3"]} -> {"List.0": "Item1", "List.1": "Item2", "List.2": "Item3"}

Summary by CodeRabbit

  • New Features

    • Introduced a new transformation component, FlattenFields, allowing users to flatten nested records into a single-level format.
    • Added a method for creating FlattenFields components dynamically.
  • Bug Fixes

    • Enhanced the flattening logic to handle various data structures effectively.
  • Tests

    • Added a comprehensive test suite for the FlattenFields transformation, covering multiple scenarios to ensure accuracy.

@lazebnyi lazebnyi requested a review from maxi297 December 18, 2024 04:11
@github-actions github-actions bot added the enhancement New feature or request label Dec 18, 2024
Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

This pull request introduces a new FlattenFields transformation component to the Airbyte CDK declarative source framework. The addition enables users to flatten nested record structures into a single-level format across multiple files, including schema definitions, model classes, component factory, transformation implementation, and corresponding unit tests. The change extends the declarative source's data transformation capabilities by providing a mechanism to simplify complex nested data structures.

Changes

File Change Summary
airbyte_cdk/sources/declarative/declarative_component_schema.yaml Added FlattenFields transformation component definition
airbyte_cdk/sources/declarative/models/declarative_component_schema.py Introduced FlattenFields class inheriting from BaseModel
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py Added create_flatten_fields method and updated component mapping
airbyte_cdk/sources/declarative/transformations/flatten_fields.py Implemented FlattenFields transformation with recursive flattening logic
unit_tests/sources/declarative/transformations/test_flatten_fields.py Created comprehensive unit tests for FlattenFields transformation

Possibly related PRs

  • feat(low-code cdk): add dynamic schema loader #104: The introduction of the DynamicSchemaLoader, SchemaTypeIdentifier, and TypesMap components relates to the new FlattenFields transformation as both enhance the schema capabilities within the declarative_component_schema.yaml file.
  • feat(low-code cdk): add KeyToSnakeCase transformation #178: The addition of the KeysToSnakeCase transformation is related to the FlattenFields transformation as both are new transformation types defined in the schema, expanding the functionality of data processing within the same framework.

Suggested reviewers

  • maxi297
  • aldogonzalez8

Hey there! 👋 Would you be interested in a quick review of this new FlattenFields transformation? I've added comprehensive tests to cover various scenarios. Wdyt? The implementation looks solid, but an extra set of eyes is always welcome! 🕵️‍♂️🔍


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9b364f3 and d5b4f65.

📒 Files selected for processing (1)
  • airbyte_cdk/sources/declarative/transformations/flatten_fields.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • airbyte_cdk/sources/declarative/transformations/flatten_fields.py

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (6)
airbyte_cdk/sources/declarative/models/declarative_component_schema.py (1)

718-721: LGTM! Would you consider adding docstring documentation?

The FlattenFields class implementation looks good and follows the established patterns. Consider adding a docstring to describe its purpose and behavior, wdyt?

 class FlattenFields(BaseModel):
+    """A transformation that flattens nested records into a single-level format.
+    
+    This transformation is useful for sources that require simplified record structures
+    on their path to manifest.
+    """
     type: Literal["FlattenFields"]
     parameters: Optional[Dict[str, Any]] = Field(None, alias="$parameters")
unit_tests/sources/declarative/transformations/test_flatten_fields.py (2)

12-50: Consider adding more test cases for edge scenarios

The current test cases cover the basic functionality well, but would you consider adding tests for:

  1. Empty records {}
  2. Records with null values
  3. Deep nesting (>2 levels)
  4. Records with special characters in keys
  5. Performance test with a large nested record

This would help ensure the transformation handles edge cases gracefully. wdyt?

@pytest.mark.parametrize(
    "input_record, expected_output",
    [
        # Empty record
        ({}, {}),
        
        # Null values
        ({"nested": {"key": None}}, {"key": None}),
        
        # Deep nesting
        (
            {"l1": {"l2": {"l3": {"value": "deep"}}}},
            {"value": "deep"}
        ),
        
        # Special characters
        ({"@special": {"$key": "value"}}, {"$key": "value"}),
        
        # Add to existing cases...
    ]
)

51-54: Consider enhancing test implementation robustness

The current implementation is clean, but would you consider:

  1. Verifying that only the expected fields are modified by making a deep copy of the input and comparing non-flattened fields
  2. Adding error handling tests for invalid inputs
  3. Adding a test helper to verify the flattening depth

Here's a possible implementation, wdyt?

from copy import deepcopy

def test_flatten_fields(input_record, expected_output):
    original_record = deepcopy(input_record)
    flattener = FlattenFields()
    flattener.transform(input_record)
    assert input_record == expected_output
    
    # Verify only expected fields were modified
    for k, v in original_record.items():
        if not isinstance(v, (dict, list)):
            assert input_record[k] == v

@pytest.mark.parametrize("invalid_input", [None, 42, "not_a_dict"])
def test_flatten_fields_error_handling(invalid_input):
    flattener = FlattenFields()
    with pytest.raises(ValueError):
        flattener.transform(invalid_input)
airbyte_cdk/sources/declarative/transformations/flatten_fields.py (1)

25-50: Consider optimizing the flattening algorithm

The current implementation is clean but could be optimized. Would you consider:

  1. Adding early returns for non-nested records
  2. Using a more memory-efficient approach for large records
  3. Adding depth limit to prevent stack overflow
  4. Handling circular references

Here's a possible optimization, wdyt?

def flatten_record(self, record: Dict[str, Any], max_depth: int = 100) -> Dict[str, Any]:
    # Early return if no nested structures
    if not any(isinstance(v, (dict, list)) for v in record.values()):
        return record.copy()
        
    transformed_record = {}
    stack = [(record, "_", 0)]  # (value, parent_key, depth)
    seen = set()  # For circular reference detection
    
    while stack:
        current_record, parent_key, depth = stack.pop()
        
        if depth > max_depth:
            raise ValueError(f"Maximum nesting depth of {max_depth} exceeded")
            
        if isinstance(current_record, dict):
            record_id = id(current_record)
            if record_id in seen:
                raise ValueError("Circular reference detected")
            seen.add(record_id)
            
            for current_key, value in current_record.items():
                new_key = (
                    f"{parent_key}.{current_key}"
                    if parent_key != "_"
                    else current_key
                )
                if isinstance(value, (dict, list)):
                    stack.append((value, new_key, depth + 1))
                else:
                    transformed_record[new_key] = value
                    
        elif isinstance(current_record, list):
            for i, item in enumerate(current_record):
                stack.append((item, f"{parent_key}.{i}", depth + 1))
                
    return transformed_record
airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (1)

597-601: Consider aligning with other transformation implementations

The implementation is simple but could be more consistent with other transformations in the factory. Would you consider:

  1. Adding parameter validation similar to other transformations
  2. Adding type hints for the return value
  3. Following the pattern used by similar transformations like create_add_fields

Here's a suggestion, wdyt?

def create_flatten_fields(
    self,
    model: FlattenFieldsModel,
    config: Config,
    **kwargs: Any
) -> FlattenFields:
    """Creates a FlattenFields transformation component.
    
    Args:
        model: The model containing the component configuration.
        config: The connector configuration.
        **kwargs: Additional keyword arguments.
        
    Returns:
        FlattenFields: The created component.
    """
    return FlattenFields(
        parameters=model.parameters or {},
    )
airbyte_cdk/sources/declarative/declarative_component_schema.yaml (1)

1855-1867: Consider adding configuration options for customizing the flattening behavior?

The schema definition for FlattenFields is quite minimal. Would it be helpful to add configuration options to customize the flattening behavior? For example:

  • separator - to specify the character used to join nested keys
  • max_depth - to limit how deep the flattening goes
  • array_handling - to specify how to handle arrays (e.g., 'expand', 'first_element', 'ignore')

This would give users more control over the transformation, wdyt?

Also, would you consider adding some examples to help users understand the transformation? Something like:

examples:
  - input: {"user": {"name": {"first": "John", "last": "Doe"}}}
    output: {"user_name_first": "John", "user_name_last": "Doe"}
  - input: {"items": [{"id": 1}, {"id": 2}]}
    output: {"items_0_id": 1, "items_1_id": 2}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between adef1e8 and 9b364f3.

📒 Files selected for processing (5)
  • airbyte_cdk/sources/declarative/declarative_component_schema.yaml (1 hunks)
  • airbyte_cdk/sources/declarative/models/declarative_component_schema.py (1 hunks)
  • airbyte_cdk/sources/declarative/parsers/model_to_component_factory.py (4 hunks)
  • airbyte_cdk/sources/declarative/transformations/flatten_fields.py (1 hunks)
  • unit_tests/sources/declarative/transformations/test_flatten_fields.py (1 hunks)

Copy link
Contributor

@aldogonzalez8 aldogonzalez8 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

APPROVED, just left minor comment.

@lazebnyi lazebnyi merged commit f222fcc into main Dec 18, 2024
20 checks passed
@lazebnyi lazebnyi deleted the lazebnyi/add-flatten-fields branch December 18, 2024 16:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants